<template>
  <el-dialog
    title="试卷下载"
    :visible.sync="dialogVisible"
    width="600px"
    @close="handleClose"
    @closed="handleClosed"
  >
      <div>
        <el-form ref="form" :model="form" label-width="130px" label-position="left">
          <el-form-item>
            <div slot="label">
              学生姓名:
              <el-popover
                placement="right"
                width="530"
                trigger="click"
              >
                <div>
                  <img src="../../../assets/exportImage/studentName.png" style="width:500px"/>
                </div>
                <i class="el-icon-warning" slot="reference"></i>
              </el-popover>
            </div>
            <el-radio-group v-model="form.stuNamePosition">
              <el-radio :label="1">卷前</el-radio>
              <el-radio :label="0">不显示</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <div slot="label">
              题型位置:
              <el-popover
                placement="right"
                width="530"
                trigger="click"
              >
                <div>
                  <img src="../../../assets/exportImage/questionType.png" style="width:500px"/>
                </div>
                <i class="el-icon-warning" slot="reference"></i>
              </el-popover>
            </div>
            <el-radio-group v-model="form.topicTypePosition">
              <el-radio :label="1">题前</el-radio>
              <el-radio :label="0">不显示</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <div slot="label">
              分值位置:
              <el-popover
                placement="right"
                width="530"
                trigger="click"
              >
                <div>
                  <img src="../../../assets/exportImage/score.png" style="width:500px"/>
                </div>
                <i class="el-icon-warning" slot="reference"></i>
              </el-popover>
            </div>
            <el-radio-group v-model="form.scorePosition">
              <el-radio :label="1">题后</el-radio>
              <el-radio :label="0">不显示</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <div slot="label">
              小题得分:
              <el-popover
                placement="right"
                width="530"
                trigger="click"
              >
                <div>
                  <img src="../../../assets/exportImage/questionScore.png" style="width:500px"/>
                </div>
                <i class="el-icon-warning" slot="reference"></i>
              </el-popover>
            </div>
            <el-radio-group v-model="form.topicScorePosition">
              <el-radio :label="1">题后</el-radio>
              <el-radio :label="0">不显示</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <div slot="label">
              学生答案:
              <el-popover
                placement="right"
                width="530"
                trigger="click"
              >
                <div>
                  <img src="../../../assets/exportImage/studentAnswer.png" style="width:500px"/>
                </div>
                <i class="el-icon-warning" slot="reference"></i>
              </el-popover>
            </div>
            <el-radio-group v-model="form.stuAnswerPosition">
              <el-radio :label="1">题后</el-radio>
              <el-radio :label="0">不显示</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <div slot="label">
              教师批注:
              <el-popover
                placement="right"
                width="530"
                trigger="click"
              >
                <div>
                  <img src="../../../assets/exportImage/teacherAnnotation.png" style="width:500px"/>
                </div>
                <i class="el-icon-warning" slot="reference"></i>
              </el-popover>
            </div>
            <el-radio-group v-model="form.teacherRemarkPosition">
              <el-radio :label="1">题后</el-radio>
              <el-radio :label="0">不显示</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <div slot="label">
              图片批注:
              <el-popover
                placement="right"
                width="530"
                trigger="click"
              >
                <div>
                  <img src="../../../assets/exportImage/imgAnnotation.png" style="width:500px"/>
                </div>
                <i class="el-icon-warning" slot="reference"></i>
              </el-popover>
            </div>
            <el-radio-group v-model="form.settlePic">
              <el-radio :label="1">题后</el-radio>
              <el-radio :label="0">不显示</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <div slot="label">
              正确答案:
              <el-popover
                placement="right"
                width="530"
                trigger="click"
              >
                <div>
                  <img src="../../../assets/exportImage/rightAnswer.png" style="width:500px"/>
                </div>
                <i class="el-icon-warning" slot="reference"></i>
              </el-popover>
            </div>
            <el-radio-group v-model="form.answerPosition">
              <el-radio :label="1">题后</el-radio>
              <el-radio :label="0">不显示</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <div slot="label">
              解析位置:
              <el-popover
                placement="right"
                width="530"
                trigger="click"
              >
                <div>
                  <img src="../../../assets/exportImage/analysis.png" style="width:500px"/>
                </div>
                <i class="el-icon-warning" slot="reference"></i>
              </el-popover>
            </div>
            <el-radio-group v-model="form.resolvePosition">
              <el-radio :label="1">题后</el-radio>
              <el-radio :label="0">不显示</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="导出格式:">
            <el-radio-group v-model="form.exportFormat">
              <el-radio label="docx">DOCX</el-radio>
              <el-radio label="doc">DOC</el-radio>
              <el-radio label="pdf">PDF</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
    <div slot="footer" class="dialog-footer">
      <span style="font-size: 14px;color: orange;">注：题目无教师批注、图片批注时自动隐藏该字段</span>
      <div>
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">下 载</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { exportStuExamPaper, getExportProgress } from '@/api/CourseTeach'

export default {
  name: 'ExportExamDia',
  data() {
    return {
      dialogVisible: false,
      needReset: false,
      // 导出类型1：课后作业，2：考核，3：成果
      type: '',
      // 课程详情
      courseInfo: {},
      // 学生id数组
      studentList: [],
      // 目录Id数组
      examIdList: [],
      form: {
        stuNamePosition: 0,
        topicTypePosition: 0,
        scorePosition: 1,
        topicScorePosition: 1,
        stuAnswerPosition: 1,
        teacherRemarkPosition: 1,
        settlePic: 1,
        answerPosition: 1,
        resolvePosition: 1,
        exportFormat: 'docx'
      },
      // 添加加载状态
      downloadLoading: null,
      downloadProgress: 0, // 添加进度百分比数据
      // 轮询定时器
      pollingTimer: null
    }
  },
  beforeDestroy() {
    // 组件销毁前清理轮询
    this.clearPolling()
    // 添加安全检查
    if (this.downloadLoading && this.downloadLoading.close) {
      this.downloadLoading.close()
    }
  },
  methods: {
    handleOpen(type, courseInfo, studentList, examIdList) {
      this.type = type
      this.courseInfo = courseInfo
      this.studentList = studentList
      this.examIdList = examIdList
      this.dialogVisible = true
    },
    handleClose() {
      this.needReset = true
      this.dialogVisible = false
      // 关闭时清理轮询
      this.clearPolling()
    },
    handleClosed() {
      if (this.needReset) {
        this.resetForm()
        this.needReset = false
      }
    },
    resetForm() {
      this.form = {
        stuNamePosition: 0,
        topicTypePosition: 0,
        scorePosition: 1,
        topicScorePosition: 1,
        stuAnswerPosition: 1,
        teacherRemarkPosition: 1,
        settlePic: 1,
        answerPosition: 1,
        resolvePosition: 1,
        exportFormat: 'docx'
      }
    },
    async handleConfirm() {
      let data = {
        ...this.form,
        studentList: this.studentList,
        examIdList: this.examIdList
      }
      let res = await exportStuExamPaper(data)
      if (res.code == 200) {
        let uuid = res.data
        // 开始轮询查询进度
        this.startPolling(uuid)
      }
    },
    // 开始轮询查询下载进度
    startPolling(uuid) {
      this.downloadLoading = this.$loading({
        lock: true,
        text: `正在导出，请稍后... ${this.downloadProgress}%`,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.clearPolling() // 清理之前的轮询
      // 立即查询一次
      this.pollDownloadProgress(uuid)
      // 设置定时器定期查询
      this.pollingTimer = setInterval(() => {
        this.pollDownloadProgress(uuid)
      }, 5000) // 每5秒查询一次
    },
    // 清理轮询定时器
    clearPolling() {
      if (this.pollingTimer) {
        clearInterval(this.pollingTimer)
        this.pollingTimer = null
      }
    },
    // 轮询查询下载进度
    async pollDownloadProgress(uuid) {
      try {
        let res = await getExportProgress(uuid)
        if (res.code == 200) {
          // 更新进度百分比
          if (res.data.progress !== undefined) {
            this.downloadProgress = res.data.progress
            // 更新Loading显示
            if (this.downloadLoading) {
              this.downloadLoading.setText(`正在导出，请稍后... ${this.downloadProgress}%`)
            }
          }
          if (res.data.status === 'SUCCESS') {
            // 下载完成，停止轮询并开始下载文件
            this.clearPolling()
            this.downloadFileWithBlob(res.data.downloadUrl)
            // TODO:确认失败状态字段
          } else if (res.data.status === 'FAILED') {
            // 下载失败，停止轮询并提示错误
            this.clearPolling()
            this.downloadLoading.close()
            this.$message.error('文件导出失败，请重试')
          }
          // 其他状态继续轮询
        }
      } catch (err) {
        console.log(err)
        this.clearPolling()
        this.downloadLoading.close()
        this.$message.error('查询下载进度失败')
      }
    },
    // 使用Blob方式下载文件（可选方案）
    async downloadFileWithBlob(url) {
      try {
        const response = await fetch(url)
        const blob = await response.blob()
        const downloadUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = downloadUrl
        link.download = `【${this.courseInfo.schedulingName}】${this.type === 1 ? '课后作业' : '考核'}：${this.courseInfo.courseName}.zip` // 设置文件名
        link.click()
        window.URL.revokeObjectURL(downloadUrl)
        // 延时关闭弹窗，给用户看到成功提示的时间
      } catch (err) {
        console.error('下载文件失败:', err)
        this.$message.error('文件下载失败')
      }finally {
        setTimeout(() => {
          this.downloadLoading.close()
          this.handleClose()
        }, 1500)
      }
    }
  }
}

</script>
<style scoped lang="scss">
::v-deep .el-form-item {
  margin-bottom: 15px !important;
}

.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
